<?php

namespace app\admin\model\house;

use think\Model;


class Owner extends Model
{


    // 表名
    protected $name = 'house_owner';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';

    // 定义时间戳字段名
    protected $createTime = 'create_time';
    protected $updateTime = 'update_time';

    // 追加属性
    protected $append = [
        'status_text',
        'create_time_text',
        'update_time_text'
    ];


    public static function init()
    {
        self::afterUpdate(function ($model) {
            if ($model->status == 1) {
                $is_house_owner = 1;
            } else {
                $is_house_owner = 0;
            }

            User::update(['is_house_owner' => $is_house_owner], ['id' => $model->user_id]);
        });

        self::afterDelete(function ($model) {
            User::update(['is_house_owner' => 0], ['id' => $model->user_id]);
        });
    }

    public function user()
    {
        return $this->hasOne('app\admin\model\User', 'id', 'user_id');
    }

    public function getStatusList()
    {
        return [0 => '待审核', 1 => '通过', 2 => '拒绝'];
    }


    public function getStatusTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['status']) ? $data['status'] : '');
        $list = $this->getStatusList();
        return isset($list[$value]) ? $list[$value] : '';
    }

    public function getCardFrontAttr($value, $data)
    {
        $value = $value ?: ($data['card_front'] ?? '');
        return $value ? cdnurl($value) : '';
    }

    public function getCardBackAttr($value, $data)
    {
        $value = $value ?: ($data['card_back'] ?? '');
        return $value ? cdnurl($value) : '';
    }

    public function getBankCardFrontAttr($value, $data)
    {
        $value = $value ?: ($data['bank_card_front'] ?? '');
        return $value ? cdnurl($value) : '';
    }

    public function getCreateTimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['create_time']) ? $data['create_time'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }


    public function getUpdateTimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['update_time']) ? $data['update_time'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }

    protected function setCreateTimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }

    protected function setUpdateTimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }


}
